/* $Id: DynamicDataSource.java,v 1.1 2011/12/05 10:13:28 zhengyongxiang Exp $ */
package com.lxx.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.lxx.utils.DataSourceDirectorUtil;

/**
 * 作为对c3p0或dbcp的DataSource的封装，以此能使系统支持多数据库
 * 
 * 这个类实际是不起作用的 TransactionSynchronizationManager
 * 
 * @see master_slave_db_debug_log_enabled参数
 * 
 *
 */
public class DynamicDataSource extends AbstractRoutingDataSource {	
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	private static final boolean logDebug = true;
	
	@Override
	protected Object determineCurrentLookupKey() {		
		String ret = DataSourceDirectorUtil.getDataSourceType();		
		
		// 为了减少master数据库的压力，这里如果发现使用了master，那么继续看是否只读事务，如果是，强制使用slave
		if (ret==null || ret.equals(DataSourceDirectorUtil.MASTER)) {						
			Integer currentTransactionIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
			
			// 返回当前service level的方法，例如：com.dongao.biz.BaseDataManager.getAllProvinces
			String serviceName = TransactionSynchronizationManager.getCurrentTransactionName();			
			if (logDebug) {
				logger.info("level=" + currentTransactionIsolationLevel + "," + serviceName);
			}
			
			if (currentTransactionIsolationLevel==null) {
				
			}
			
			if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { // 只读事务肯定使用SLAVE					
				ret = DataSourceDirectorUtil.SLAVE;
				
				if (logDebug) {
					logger.info("readOnly");
				}
			}
		}
		
		
		if (logDebug) {
			logger.info(ret);
		}
		
		return ret;
	}	
	
}
